package com.leyou.interceptors;

import com.leyou.common.auth.entity.Payload;
import com.leyou.common.auth.entity.UserInfo;
import com.leyou.common.auth.utils.JwtUtils;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.threadlocals.UserHolder;
import com.leyou.common.utils.CookieUtils;
import com.leyou.config.JwtProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Eric
 * @version v1.0
 * @package com.leyou.interceptors
 * @date 2019/7/11 16:58
 * @description:
 **/
@Slf4j
public class UserInterceptor implements HandlerInterceptor {


    private JwtProperties pro;

    public UserInterceptor(JwtProperties pro) {
        this.pro = pro;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

        try {
            String token = CookieUtils.getCookieValue(request, pro.getUser().getCookieName());

            Payload<UserInfo> payload = JwtUtils.getInfoFromToken(token, pro.getPublicKey(), UserInfo.class);

            //保存用户到ThreadLocal中
            UserHolder.setUser(payload.getUserInfo().getId());
            log.info("校验用户成功，用户为：{}",payload.getUserInfo().getUsername());
            return true;
        } catch (Exception e) {

            // 解析失败，不继续向下
            log.error("【购物车服务】解析用户信息失败！", e.getMessage(),e);
            return false;
        }

    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {

        UserHolder.removeUser();
    }
}
